﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;

namespace commonImportPlugin.Configs.Base
{
    /// <summary>
    /// 基础接口类
    /// </summary>
    public interface IcommonBase
    {
        /// <summary>
        /// 工厂配置
        /// </summary>
        string factory { set; get; }

        /// <summary>
        /// 文件扩展名
        /// </summary>  
        string fileFilterRules { set; get; }
        /// <summary>
        /// 初始化配置
        /// </summary>
        void Init();
    }
    public class ConfigsBase
    {
        //公共变量
        static public Dictionary<string, string> configs;//原始配置键值对
        //初始化
        static  bool isInitSucceed = false;

        /// <summary>
        /// 加载配置键值对
        /// </summary>
        /// <param name="_configs"></param>
        public void LoadConfig(Dictionary<string, string> _configs)
        {
            configs = _configs;
            isInitSucceed = true;
        }

        /// <summary>
        /// 判断所给的键值是否存在
        /// </summary>
        /// <param name="keyName">键值名</param>
        /// <returns>true存在，false不存在</returns>
        public bool IsKeyExist(string keyName)
        {
            if (!isInitSucceed)
                throw new Exception("执行IsKeyExist函数前，请执行LoadConfig函数初始化配置！");
            
            if (configs.ContainsKey(keyName))
                return true;

            return false;
        }

        /// <summary>
        /// 判断所给的键值是否为空
        /// </summary>
        /// <param name="keyName">键值名</param>
        /// <returns>true不为空，false空</returns>
        public bool IsKeyEmpty(string keyName)
        {
            if (!isInitSucceed)
                throw new Exception("执行IsKeyEmpty函数前，请执行LoadConfig函数初始化配置！");

            if (!configs.ContainsKey(keyName))
                return true;

            if(string.IsNullOrEmpty(configs[keyName]))
                return true;

            return false;
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <param name="configPath">配置文件路径</param>
        /// <returns></returns>
        public Dictionary<string, string> ReadConfigs(string configPath)
        {
            try
            {
                Dictionary<string, string> config = new Dictionary<string, string>();

                XmlDocument xmlDoc = new XmlDocument();
                XmlReaderSettings settings = new XmlReaderSettings();
                settings.IgnoreComments = true;//忽略注释
                XmlReader reader = XmlReader.Create(configPath, settings);
                xmlDoc.Load(reader);

                var allRootElements = xmlDoc.SelectSingleNode("configuration").ChildNodes;
                foreach (XmlNode _rootElement in allRootElements)
                {
                    XmlElement rootElement = (XmlElement)_rootElement;
                    string rootName = rootElement.GetAttribute("Name").Substring(0, 1);
                    if (rootName != "-")
                    {
                        ReadNodeValues(_rootElement, config);
                    }
                    else
                        continue;
                }
                return config;
            }
            catch (Exception e)
            {
                throw new Exception("读取配置文件失败！Error Messages:"+e.Message);
            }
        }

        /// <summary>
        /// 读取一节点下面的内容将其放在Dictionary<string, string>中
        /// </summary>
        /// <param name="node">节点</param>
        /// <param name="configs"></param>
        /// <returns></returns>
        private bool ReadNodeValues(XmlNode node, Dictionary<string, string> configs)
        {
            try
            {
                foreach (XmlElement Xe in node)
                {
                    string XeName = Xe.Name;//节点名
                    string XeInnerText = Xe.InnerText;//节点值
                    int childCount = ((XmlNode)Xe).ChildNodes.Count;

                    if (childCount == 1)
                    {
                        configs.Add(XeName, XeInnerText.Trim());
                    }
                    else//有二级目录
                    {
                        XmlNode xmlNode = Xe;
                        string xnName = xmlNode.Name;
                        string xnValue = "";
                        foreach (XmlElement xe in xmlNode)
                        {
                            string xeInnerText = xe.InnerText;//节点值
                            xnValue += (xeInnerText.Trim() + "&");
                        }
                        configs.Add(xnName, xnValue.Trim('&'));
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 将string 转为string数组
        /// </summary>
        /// <param name="originString">要转的字符</param>
        /// <returns>转完的结果</returns>
        public string[] ToStringArrays(string originString)
        {
            try
            {
                if (string.IsNullOrEmpty(originString))
                    return null;

                string[] originStrings = originString.Split('&');
                return originStrings;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
        /// <summary>
        /// 将string 转为int数组
        /// </summary>
        /// <param name="originString">要转的字符</param>
        /// <returns>转完的结果</returns>
        public int[] ToIntArrays(string originString)
        {
            try
            {
                int[] finalArrays = null;
                if (string.IsNullOrEmpty(originString))
                    return null;
                string[] originStrings = originString.Split('&');
                finalArrays = Array.ConvertAll<string, int>(originStrings, s => int.Parse(s));
                return finalArrays;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}
